import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart' show SelectableText;
import 'package:flutter/services.dart';
import 'package:macos_ui/macos_ui.dart';
import '../models/mcp_tool.dart';

/// 结果和日志查看器组件（带标签页）
class ResultAndLogViewer extends StatefulWidget {
  final McpToolResult? result;
  final List<String> logs;
  final VoidCallback onClearLogs;

  const ResultAndLogViewer({
    super.key,
    this.result,
    required this.logs,
    required this.onClearLogs,
  });

  @override
  State<ResultAndLogViewer> createState() => _ResultAndLogViewerState();
}

class _ResultAndLogViewerState extends State<ResultAndLogViewer> {
  final ScrollController _logScrollController = ScrollController();
  bool _autoScroll = true; // 是否自动滚动到最新日志
  bool _showScrollToBottom = false; // 是否显示“跳到最新”按钮

  @override
  void initState() {
    super.initState();
    _logScrollController.addListener(_onLogScroll);
  }

  @override
  void dispose() {
    _logScrollController.removeListener(_onLogScroll);
    _logScrollController.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(ResultAndLogViewer oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 当日志更新时，如果处于自动滚动模式，滚动到底部
    if (widget.logs.length != oldWidget.logs.length && _autoScroll) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToBottom();
      });
    }
  }

  void _onLogScroll() {
    if (!_logScrollController.hasClients) return;

    final isAtBottom = _logScrollController.position.pixels >=
        _logScrollController.position.maxScrollExtent - 50;

    if (isAtBottom) {
      if (!_autoScroll) {
        setState(() {
          _autoScroll = true;
          _showScrollToBottom = false;
        });
      }
    } else {
      if (_autoScroll) {
        setState(() {
          _autoScroll = false;
          _showScrollToBottom = true;
        });
      }
    }
  }

  void _scrollToBottom() {
    if (_logScrollController.hasClients) {
      _logScrollController.animateTo(
        _logScrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
      setState(() {
        _autoScroll = true;
        _showScrollToBottom = false;
      });
    }
  }

  String _formatJson(dynamic data) {
    try {
      const encoder = JsonEncoder.withIndent('  ');
      return encoder.convert(data);
    } catch (e) {
      return data.toString();
    }
  }

  void _copyToClipboard(BuildContext context, String text) {
    Clipboard.setData(ClipboardData(text: text));
    showMacosAlertDialog(
      context: context,
      builder: (context) => MacosAlertDialog(
        appIcon: const Icon(CupertinoIcons.checkmark_circle),
        title: const Text('已复制'),
        message: const Text('内容已复制到剪贴板'),
        primaryButton: PushButton(
          controlSize: ControlSize.large,
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('确定'),
        ),
      ),
    );
  }

  Color _getLogColor(String log) {
    if (log.contains('✅') || log.contains('成功')) {
      return MacosColors.systemGreenColor;
    } else if (log.contains('❌') || log.contains('失败') || log.contains('错误')) {
      return MacosColors.systemRedColor;
    } else if (log.contains('⚠️') || log.contains('警告')) {
      return MacosColors.systemOrangeColor;
    } else if (log.contains('🔧') || log.contains('🧪')) {
      return MacosColors.systemYellowColor;
    } else if (log.contains('📡') || log.contains('📤') || log.contains('📥')) {
      return MacosColors.systemTealColor;
    }
    return MacosTheme.of(context).typography.body.color ?? MacosColors.labelColor;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 上部分：执行结果（占3份）
        Expanded(
          flex: 3,
          child: Column(
            children: [
              // 结果标题栏
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: MacosTheme.of(context).canvasColor,
                  border: Border(
                    bottom: BorderSide(color: MacosTheme.of(context).dividerColor),
                  ),
                ),
                child: Row(
                  children: [
                    Icon(CupertinoIcons.doc_text, size: 16),
                    const SizedBox(width: 8),
                    Text(
                      '执行结果',
                      style: MacosTheme.of(context).typography.body.copyWith(
                            fontWeight: FontWeight.bold,
                            fontSize: 13,
                          ),
                    ),
                  ],
                ),
              ),
              Expanded(child: _buildResultTab()),
            ],
          ),
        ),
        // 分隔线
        Container(height: 1, color: MacosTheme.of(context).dividerColor),
        // 下部分：调试日志（占2份）
        Expanded(
          flex: 2,
          child: _buildLogTab(),
        ),
      ],
    );
  }

  Widget _buildResultTab() {
    if (widget.result == null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              CupertinoIcons.doc_text,
              size: 48,
              color: MacosTheme.of(context).typography.body.color?.withOpacity(0.3),
            ),
            const SizedBox(height: 16),
            Text(
              '暂无结果',
              style: MacosTheme.of(context).typography.body.copyWith(
                    color: MacosTheme.of(context).typography.body.color?.withOpacity(0.5),
                  ),
            ),
            const SizedBox(height: 8),
            Text(
              '执行工具后结果将显示在这里',
              style: MacosTheme.of(context).typography.caption1.copyWith(
                    color: MacosTheme.of(context).typography.body.color?.withOpacity(0.5),
                  ),
            ),
          ],
        ),
      );
    }

    final formattedResult = _formatJson(widget.result!.result);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // Header
        Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: widget.result!.success
                ? MacosColors.systemGreenColor.withOpacity(0.1)
                : MacosColors.systemRedColor.withOpacity(0.1),
            border: Border(
              bottom: BorderSide(color: MacosTheme.of(context).dividerColor),
            ),
          ),
          child: Row(
            children: [
              Icon(
                widget.result!.success
                    ? CupertinoIcons.checkmark_circle_fill
                    : CupertinoIcons.xmark_circle_fill,
                color: widget.result!.success
                    ? MacosColors.systemGreenColor
                    : MacosColors.systemRedColor,
                size: 20,
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      widget.result!.success ? '成功' : '错误',
                      style: MacosTheme.of(context)
                          .typography
                          .body
                          .copyWith(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      widget.result!.toolName,
                      style: MacosTheme.of(context).typography.caption1.copyWith(
                            color: MacosTheme.of(context)
                                .typography
                                .body
                                .color
                                ?.withOpacity(0.7),
                          ),
                    ),
                  ],
                ),
              ),
              MacosIconButton(
                icon: const Icon(CupertinoIcons.doc_on_clipboard, size: 16),
                onPressed: () => _copyToClipboard(
                  context,
                  widget.result!.success ? formattedResult : widget.result!.error ?? '',
                ),
              ),
            ],
          ),
        ),
        // Result content
        Expanded(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(12),
            child: widget.result!.success
                ? _buildSuccessContent(context, formattedResult)
                : _buildErrorContent(context),
          ),
        ),
      ],
    );
  }

  Widget _buildSuccessContent(BuildContext context, String formattedResult) {
    return Container(
      decoration: BoxDecoration(
        color: MacosTheme.of(context).brightness == Brightness.dark
            ? MacosColors.black.withOpacity(0.3)
            : MacosColors.white.withOpacity(0.5),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: MacosTheme.of(context).dividerColor),
      ),
      padding: const EdgeInsets.all(16),
      child: SelectableText(
        formattedResult,
        style: MacosTheme.of(context).typography.body.copyWith(
              fontFamily: 'Courier',
              fontSize: 13,
            ),
      ),
    );
  }

  Widget _buildErrorContent(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: MacosColors.systemRedColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: MacosColors.systemRedColor.withOpacity(0.3)),
      ),
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(
                CupertinoIcons.exclamationmark_triangle,
                color: MacosColors.systemRedColor,
                size: 20,
              ),
              const SizedBox(width: 8),
              Text(
                '错误详情',
                style: MacosTheme.of(context).typography.body.copyWith(
                      fontWeight: FontWeight.bold,
                      color: MacosColors.systemRedColor,
                    ),
              ),
            ],
          ),
          const SizedBox(height: 12),
          SelectableText(
            widget.result!.error ?? '未知错误',
            style: MacosTheme.of(context).typography.body.copyWith(
                  fontFamily: 'Courier',
                  fontSize: 13,
                ),
          ),
        ],
      ),
    );
  }

  Widget _buildLogTab() {
    return Column(
      children: [
        // 日志工具栏
        Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: MacosTheme.of(context).canvasColor,
            border: Border(
              bottom: BorderSide(color: MacosTheme.of(context).dividerColor),
            ),
          ),
          child: Row(
            children: [
              Icon(CupertinoIcons.text_alignleft, size: 16),
              const SizedBox(width: 8),
              Text(
                '调试日志 (${widget.logs.length})',
                style: MacosTheme.of(context).typography.body.copyWith(
                      fontWeight: FontWeight.bold,
                      fontSize: 13,
                    ),
              ),
              const Spacer(),
              // 自动滚动状态指示器
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                  color: _autoScroll
                      ? MacosColors.systemGreenColor.withOpacity(0.2)
                      : MacosColors.systemGrayColor.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      _autoScroll ? CupertinoIcons.play_arrow_solid : CupertinoIcons.pause_solid,
                      color: _autoScroll
                          ? MacosColors.systemGreenColor
                          : MacosColors.systemGrayColor,
                      size: 12,
                    ),
                    const SizedBox(width: 4),
                    Text(
                      _autoScroll ? '自动' : '暂停',
                      style: MacosTheme.of(context).typography.caption2.copyWith(
                            color: _autoScroll
                                ? MacosColors.systemGreenColor
                                : MacosColors.systemGrayColor,
                            fontSize: 11,
                          ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 8),
              MacosIconButton(
                icon: const Icon(CupertinoIcons.doc_on_clipboard, size: 16),
                onPressed: () => _copyToClipboard(context, widget.logs.join('\n')),
              ),
              const SizedBox(width: 4),
              MacosIconButton(
                icon: const Icon(CupertinoIcons.trash, size: 16),
                onPressed: widget.onClearLogs,
              ),
            ],
          ),
        ),
        // 日志内容
        Expanded(
          child: Stack(
            children: [
              Container(
                color: MacosTheme.of(context).brightness == Brightness.dark
                    ? MacosColors.black
                    : const Color(0xFF1E1E1E),
                child: widget.logs.isEmpty
                    ? Center(
                        child: Text(
                          '暂无日志',
                          style: MacosTheme.of(context).typography.body.copyWith(
                                color: MacosColors.systemGrayColor,
                              ),
                        ),
                      )
                    : ListView.builder(
                        controller: _logScrollController,
                        padding: const EdgeInsets.all(8),
                        itemCount: widget.logs.length,
                        itemBuilder: (context, index) {
                          final log = widget.logs[index];
                          return Padding(
                            padding: const EdgeInsets.symmetric(vertical: 2),
                            child: SelectableText(
                              log,
                              style: MacosTheme.of(context).typography.body.copyWith(
                                    color: _getLogColor(log),
                                    fontFamily: 'Courier',
                                    fontSize: 11,
                                  ),
                            ),
                          );
                        },
                      ),
              ),
              // "跳到最新"悬浮按钮
              if (_showScrollToBottom)
                Positioned(
                  right: 16,
                  bottom: 16,
                  child: PushButton(
                    controlSize: ControlSize.regular,
                    onPressed: _scrollToBottom,
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: const [
                        Icon(CupertinoIcons.arrow_down, size: 14),
                        SizedBox(width: 6),
                        Text('跳到最新', style: TextStyle(fontSize: 12)),
                      ],
                    ),
                  ),
                ),
            ],
          ),
        ),
      ],
    );
  }
}
